package com.bluezone.dec.system.controller;

import com.bluezone.dec.common.JsonResult;
import com.bluezone.dec.common.PageEntity;
import com.bluezone.dec.common.SystemConstant;
import com.bluezone.dec.system.entity.RectPlan;
import com.bluezone.dec.system.service.EntRectRecordService;
import com.bluezone.dec.system.service.EntRelRectService;
import com.bluezone.dec.system.service.RectPlanService;
import com.bluezone.dec.system.vo.EnterpriseRelatedPlanVo;
import com.bluezone.dec.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HHL
 * @description 专项整治计划
 * @date 2018/10/12 - 10:04
 */
@Api(tags = "专项行动数据录入/专项整治计划")
@RestController
@RequestMapping("/dec/plan")
public class SpecialRectificationPlanController {

    private static Logger log = LoggerFactory.getLogger(SpecialRectificationPlanController.class);

    @Autowired
    private RectPlanService rectPlanService;

    @Autowired
    private EntRelRectService entRelRectService;

    @Autowired
    private EntRectRecordService entRectRecordService;

    @ApiOperation("从redis缓存中获取所有专项整治计划[plan]信息")
    @GetMapping("/find-all")
    public List getPlanListFromRedis() {
        return rectPlanService.getPlanListFromRedis();
    }

    @ApiOperation("通过企业专项整治计划id查询计划详细信息及其对应的关联的企业id集合信息")
    @GetMapping("/detail")
    public JsonResult getPlanRelEnterpriseById(String id) {

        Map map = new HashMap();

        RectPlan rectPlan = null;
        try {
            rectPlan = rectPlanService.get(id);
        } catch (Exception e) {
            log.warn("不存在此专项整治计划", e);
        }

        List<String> entIds = entRelRectService.findPlanRelEntIdsByRectPlanId(id);

        map.put("rectPlan", rectPlan);
        map.put("entIds", entIds);

        return new JsonResult().ok(map);

    }

    @ApiOperation("修改专项整治计划")
    @PostMapping("/update")
    public JsonResult updatePlanByPlanId(@RequestBody EnterpriseRelatedPlanVo enterpriseRelatedPlanVo) {

        if (null != enterpriseRelatedPlanVo) {

            try {
                rectPlanService.update(enterpriseRelatedPlanVo.getRectPlan());
            } catch (Exception e) {
                log.warn("专项整治计划修改失败", e);
            }

            /* 从专项整治计划企业关联表中搜索出该id对应的关联企业并删除 */
            entRelRectService.deltePlanRelateEnterpeise(enterpriseRelatedPlanVo);

            /* 插入修改的计划与企业关联关系 */
            entRelRectService.saveChang4PlanRelateEnterpeise(enterpriseRelatedPlanVo);
        }
        return new JsonResult().ok();
    }

    @ApiOperation("根据计划id列表删除整治计划级联整治记录表以及企业整治关联表")
    @PostMapping("delete-cascade")
    public JsonResult deletePlanByIdCascade(@RequestBody List<String> planIds) {

        int i;
        int deletePlanCount = 0;
        int deleteRecordCount = 0;
        int deleteRelationshipCount = 0;

        if (!StringUtils.isEmpty(planIds)) {
            for (i = 0; i < planIds.size(); i++) {
                deletePlanCount = rectPlanService.deletePlanById(planIds.get(i));
                deleteRecordCount = entRectRecordService.deleteRecordByPlanId(planIds.get(i));
                deleteRelationshipCount = entRelRectService.deleteRelationshipByPlanId(planIds.get(i));
            }
        }

        if (deletePlanCount == 0 && deleteRecordCount == 0 && deleteRelationshipCount == 0) {
            return new JsonResult().error();
        }

        return new JsonResult().ok();
    }

    @ApiOperation("根据传递的参数，分页查询专项整治计划数据")
    @GetMapping("/page")
    public JsonResult getPlanListByPage(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = SystemConstant.PAGE_SIZE) int pageSize) {

        Map<String, Object> params = new HashMap<>();
        PageEntity<RectPlan> planListPage = null;

        params.put("pageNum", pageNum);
        params.put("pageSize", pageSize);

        if (params.size() == 0) {
            return new JsonResult().paramsError();
        }

        try {
            planListPage = rectPlanService.findByParams(params);
        } catch (Exception e) {
            log.warn("数据库计划表没有数据，无法进行分页哟", e);
        }

        return new JsonResult().ok(planListPage);
    }

    @ApiOperation("企业专项整治计划  查询所有的专项整治计划id及其对应的名称")
    @GetMapping("/all-plans")
    public JsonResult findAllRectPlan() {
        List<RectPlan> planList = null;
        planList = rectPlanService.findAllRectPlan();
        return new JsonResult().ok(planList);
    }

    @ApiOperation("专项整治计划 查询该整治计划名称是否已存在")
    @GetMapping("/find-name")
    public JsonResult findPlanName(@RequestParam(value = "rectName", required = true) String rectName) {

        int planNameCount = rectPlanService.findPlanName(rectName.trim());

        if (planNameCount == 0) {
            return new JsonResult().none();
        }

        return new JsonResult().exist();
    }

    @ApiOperation("添加专项整治计划")
    @PostMapping("/add")
    public JsonResult addRemediationPlan(@RequestBody EnterpriseRelatedPlanVo enterpriseRelatedPlanVo) {

        if (null != enterpriseRelatedPlanVo) {

            enterpriseRelatedPlanVo.getRectPlan().setId(UUIDUtils.randomUUID());
            enterpriseRelatedPlanVo.getRectPlan().setUpdateTime(new Date());

            try {
                rectPlanService.save(enterpriseRelatedPlanVo.getRectPlan());
            } catch (Exception e) {
                log.warn("专项整治计划保存失败", e);
            }

            /* 保存进 专项整治计划企业关联表 */
            entRelRectService.saveChang4PlanRelateEnterpeise(enterpriseRelatedPlanVo);

        }
        return new JsonResult().ok();
    }

    @ApiOperation("从redis缓存中获取所有企业信息")
    @GetMapping("/enterprises")
    public JsonResult getEnterpriseListFromRedis() {
        List entList = rectPlanService.getEnterpriseListFromRedis();
        return new JsonResult().ok(entList);
    }

}
